import React, { useState, useCallback } from 'react';
import { LineChart, Line, PieChart, Pie, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Cell } from 'recharts';
import { useEffect } from 'react';

//websocked
import { io, Socket } from 'socket.io-client';
let socket: Socket | null = null;

import axios from 'axios';
axios.defaults.baseURL = 'http://127.0.0.1:3000/';
// 模拟数据 - 与about和home2页面保持一致格式
const topMetrics = [
  { title: '线上总内容', value: '373.5W+', icon: '📄', trend: '↑ 2.4%' },
  { title: '线上内容', value: '368 个', icon: '📊', trend: '↑ 12' },
  { title: '日新增评论', value: '8874 个', icon: '💬', trend: '↑ 15.2%' },
  { title: '较昨日新增', value: '2.8%', icon: '📈', trend: '↑ 0.5%' },
];

// 内容类别占比数据
const contentTypeData = [
  { name: '纯文本', value: 46, color: '#8884d8' },
  { name: '图文类', value: 40, color: '#82ca9d' },
  { name: '视频类', value: 14, color: '#ffc658' },
];

// 热门内容数据
const popularContentData = [
  { rank: 1, title: '经济日报:财政政策要精准发力', clicks: '346.3W+', growth: '35% ↑' },
  { rank: 2, title: '经济日报:财政政策要精准发力', clicks: '346.3W+', growth: '35% ↑' },
  { rank: 3, title: '经济日报:财政政策要精准发力', clicks: '346.3W+', growth: '35% ↑' },
  { rank: 4, title: '经济日报:财政政策要精准发力', clicks: '346.3W+', growth: '35% ↑' },
  { rank: 5, title: '经济日报:财政政策要精准发力', clicks: '346.3W+', growth: '35% ↑' },
];

const Appear: React.FC = () => {
  const [contentTrendData, setContentTrendData] = useState([]);
  const getLineChart = useCallback(async () => {
    try {
      const res = await axios.get('vlist');
      console.log('获取新数据:', res.data.videoList);
      setContentTrendData(res.data.videoList);
    } catch (error) {
      console.error('获取数据失败:', error);
    }
  }, []);

useEffect(() => {
    // 初始化数据
    getLineChart();

    // 创建 socket 连接
    if (!socket) {
      socket = io('http://localhost:3000', {
        withCredentials: true,
        transports: ['websocket']
      });

      socket.on('connect', () => {
        console.log('Socket connected!');
      });

      socket.on('connect_error', (error) => {
        console.error('Socket connection error:', error);
      });
    }

    // 监听数据更新事件
    socket.on('dataUpdate', () => {
      console.log('收到数据更新事件');
      getLineChart();
    });

    // 清理函数
    return () => {
      socket?.off('dataUpdate');
    };
  }, [getLineChart]); // 依赖 getLineChart


useEffect(() => {
  getLineChart();
  
}, []);
  return (
    <div style={{ padding: '20px', backgroundColor: '#f5f5f5', minHeight: '100vh' }}>
      {/* 欢迎标题 */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
        <h1 style={{ margin: 0, color: '#333' }}>欢迎回来, 张三</h1>
      </div>

      {/* 顶部指标卡片 */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '20px', marginBottom: '30px' }}>
        {topMetrics.map((metric, index) => (
          <div key={index} style={{
            backgroundColor: 'white',
            padding: '20px',
            borderRadius: '8px',
            boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
            textAlign: 'center'
          }}>
            <div style={{ fontSize: '24px', marginBottom: '10px' }}>{metric.icon}</div>
            <h3 style={{ margin: '0 0 10px 0', color: '#666', fontSize: '14px' }}>{metric.title}</h3>
            <p style={{ fontSize: '22px', fontWeight: 'bold', margin: '0 0 5px 0' }}>{metric.value}</p>
            <p style={{ fontSize: '12px', color: 'green', margin: 0 }}>{metric.trend}</p>
          </div>
        ))}
      </div>

      {/* 内容数据趋势图 */}
      <div style={{ backgroundColor: 'white', padding: '20px', borderRadius: '8px', boxShadow: '0 2px 4px rgba(0,0,0,0.1)', marginBottom: '30px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
          <h2 style={{ margin: 0, fontSize: '18px', color: '#333' }}>点赞量与收藏量趋势 (实时)</h2>
          <div style={{ display: 'flex', gap: '20px', alignItems: 'center' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
              <div style={{ width: '12px', height: '2px', backgroundColor: '#8884d8' }}></div>
              <span style={{ fontSize: '12px', color: '#666' }}>点赞数</span>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
              <div style={{ width: '12px', height: '2px', backgroundColor: '#82ca9d' }}></div>
              <span style={{ fontSize: '12px', color: '#666' }}>收藏数</span>
            </div>
          </div>
        </div>
        <div style={{ height: '300px' }}>
          <ResponsiveContainer width="100%" height="100%">
            <LineChart data={contentTrendData} margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
              <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#f0f0f0" />
              <XAxis dataKey="title" tick={{ fontSize: 12 }} axisLine={false} tickLine={false} />
              <YAxis tick={{ fontSize: 12 }} axisLine={false} tickLine={false} />
              <Tooltip
                contentStyle={{ borderRadius: '8px', border: 'none', boxShadow: '0 4px 12px rgba(0,0,0,0.15)' }}
                formatter={(value, name) => {
                  const label = name === 'likes' ? '点赞数' : '收藏数';
                  return [`${value}`, label];
                }}
              />
              <Line
                type="monotone"
                dataKey="likes"
                stroke="#8884d8"
                strokeWidth={2}
                dot={{ r: 4, strokeWidth: 2 }}
                activeDot={{ r: 6, strokeWidth: 0, fill: '#8884d8' }}
                name="likes"
              />
              <Line
                type="monotone"
                dataKey="favorites"
                stroke="#82ca9d"
                strokeWidth={2}
                dot={{ r: 4, strokeWidth: 2 }}
                activeDot={{ r: 6, strokeWidth: 0, fill: '#82ca9d' }}
                name="favorites"
              />
            </LineChart>
          </ResponsiveContainer>
        </div>
      </div>

      {/* 底部内容区 */}
      <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: '20px' }}>
        {/* 线上热门内容表格 */}
        <div style={{ backgroundColor: 'white', padding: '20px', borderRadius: '8px', boxShadow: '0 2px 4px rgba(0,0,0,0.1)' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '20px' }}>
            <h2 style={{ margin: 0, fontSize: '18px', color: '#333' }}>线上热门内容</h2>
            <button style={{ backgroundColor: 'transparent', border: 'none', color: '#1890ff', cursor: 'pointer', fontSize: '14px' }}>查看更多</button>
          </div>

          {/* 内容类型标签 */}
          <div style={{ display: 'flex', gap: '10px', marginBottom: '15px' }}>
            <button style={{ backgroundColor: '#1890ff', color: 'white', border: 'none', borderRadius: '4px', padding: '5px 10px', cursor: 'pointer' }}>文本</button>
            <button style={{ backgroundColor: 'transparent', color: '#666', border: '1px solid #ddd', borderRadius: '4px', padding: '5px 10px', cursor: 'pointer' }}>图文</button>
            <button style={{ backgroundColor: 'transparent', color: '#666', border: '1px solid #ddd', borderRadius: '4px', padding: '5px 10px', cursor: 'pointer' }}>视频</button>
          </div>

          {/* 纯CSS实现的表格 */}
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead>
                <tr style={{ backgroundColor: '#f5f5f5' }}>
                  <th style={{ padding: '12px 8px', textAlign: 'left', fontWeight: 'bold', color: '#333', borderBottom: '1px solid #eee' }}>排名</th>
                  <th style={{ padding: '12px 8px', textAlign: 'left', fontWeight: 'bold', color: '#333', borderBottom: '1px solid #eee' }}>内容标题</th>
                  <th style={{ padding: '12px 8px', textAlign: 'left', fontWeight: 'bold', color: '#333', borderBottom: '1px solid #eee' }}>点击量</th>
                  <th style={{ padding: '12px 8px', textAlign: 'left', fontWeight: 'bold', color: '#333', borderBottom: '1px solid #eee' }}>日涨量</th>
                </tr>
              </thead>
              <tbody>
                {popularContentData.map((item) => (
                  <tr key={item.rank} style={{ cursor: 'pointer' }} onMouseOver={(e) => e.currentTarget.style.backgroundColor = '#f9f9f9'}
                    onMouseOut={(e) => e.currentTarget.style.backgroundColor = 'transparent'}>
                    <td style={{ padding: '12px 8px', borderBottom: '1px solid #eee' }}>{item.rank}</td>
                    <td style={{ padding: '12px 8px', borderBottom: '1px solid #eee', maxWidth: '200px', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{item.title}</td>
                    <td style={{ padding: '12px 8px', borderBottom: '1px solid #eee' }}>{item.clicks}</td>
                    <td style={{ padding: '12px 8px', borderBottom: '1px solid #eee', color: 'green' }}>{item.growth}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        {/* 内容类别占比饼图 */}
        <div style={{ backgroundColor: 'white', padding: '20px', borderRadius: '8px', boxShadow: '0 2px 4px rgba(0,0,0,0.1)' }}>
          <h2 style={{ margin: '0 0 20px 0', fontSize: '18px', color: '#333' }}>内容类别占比</h2>
          <div style={{ height: '250px' }}>
            <ResponsiveContainer width="100%" height="100%">
              <PieChart>
                <Pie
                  data={contentTypeData}
                  cx="50%"
                  cy="50%"
                  innerRadius={60}
                  outerRadius={90}
                  paddingAngle={2}
                  dataKey="value"
                  label={({ name, percent }) => `${name} ${((percent ?? 0) * 100).toFixed(0)}%`}
                  labelLine={false}
                >
                  {contentTypeData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip formatter={(value) => [`${value}%`, '占比']} />
              </PieChart>
            </ResponsiveContainer>
          </div>
          <div style={{ display: 'flex', justifyContent: 'center', gap: '20px', marginTop: '10px' }}>
            {contentTypeData.map((item, index) => (
              <div key={index} style={{ display: 'flex', alignItems: 'center' }}>
                <div style={{ width: '12px', height: '12px', backgroundColor: item.color, borderRadius: '50%', marginRight: '5px' }}></div>
                <span style={{ fontSize: '12px', color: '#666' }}>{item.name}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

export default Appear;